//
//  VideoDetailViewController.m
//  Fireball
//
//  Created by 俞渊华 on 2017/12/23.
//  Copyright © 2017年 俞渊华. All rights reserved.
//

#import "VideoDetailViewController.h"
#import "NewsPlayerView.h"
#import "PlayerKitContainer.h"
#import "NewsUserView.h"
#import "NewsShareView.h"
#import "NewsCommentTool.h"
#import "ZInputToolbar.h"
#import "CommentSectionView.h"
#import "CommentCell.h"
#import "MoreReplyView.h"

#import "AticleDetailModel.h"


static NSString * const VideoDataSourceURLPath = @"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4";

@interface VideoDetailViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
CommentToolDelegate,
ZInputToolbarDelegate,
PlayerKitContainerDelegate
>
@property(nonatomic, strong)NewsPlayerView *playerView;
@property(nonatomic, strong)PlayerKitContainer *playerontainer;
/// 作者视图
@property(nonatomic, strong)NewsUserView *userView;
/// 标题
@property(nonatomic, strong)UILabel *titleLabel;

@property(nonatomic, strong)UITableView *tableView;

@property(nonatomic, strong)NewsCommentTool *commentTool;
@property(nonatomic, strong)ZInputToolbar *inputToolbar;

@property(nonatomic, strong)UIView *headerView;
@property(nonatomic, strong)NewsShareView *shareView;
@property(nonatomic, strong)UIView *headerLine;
@property(nonatomic, strong)UILabel *allCommentLabel;

@property(nonatomic, strong)NSMutableArray *commentArray;
@property(nonatomic, strong)AticleDetailModel *detailModel;

@property(nonatomic, assign)CGFloat videoHeight;
@property(nonatomic, assign)BOOL fullScreen;

@property(nonatomic, strong)NSMutableDictionary *commentDict;
/// 要回复的评论
@property(nonatomic, strong)AticleComment *commentModel;
@property(nonatomic, assign)BOOL commentSub;

@end

@implementation VideoDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.xm_backgroundColor = [UIColor clearColor];
    self.commentArray = [NSMutableArray array];
    self.videoHeight = SCREEN_WIDTH * (9.0/16);

    
    self.playerView = [[NewsPlayerView alloc] init];
    [self.view addSubview:self.playerView];
    [self.view addSubview:self.playerontainer];
    
    self.userView = [[NewsUserView alloc]init];
    [self.view addSubview:self.userView];
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.textColor = [UIColor xm_jetblackColor];
    self.titleLabel.font = [UIFont xm_medium:22.0];
    [self.view addSubview:self.titleLabel];
    
    
    [self.view addSubview:self.commentTool];
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    self.headerLine = [[UIView alloc] init];
    self.headerLine.backgroundColor = [UIColor xm_splitlineColor];
    [self.headerView addSubview:_headerLine];
    self.allCommentLabel = [[UILabel alloc] init];
    self.allCommentLabel.font = [UIFont xm_medium:17.0];
    self.allCommentLabel.textColor = [UIColor xm_jetblackColor];
    self.allCommentLabel.text = @"全部评论";
    [self.headerView addSubview:self.allCommentLabel];
    
    self.tableView.tableHeaderView = self.headerView;
    [self.view addSubview:self.tableView];
    
    self.shareView = [[NewsShareView alloc] init];
    [self.headerView addSubview:self.shareView];
    
    
    [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self.view);
        make.height.mas_equalTo(self.videoHeight + STATUSBARHEIGHT);
    }];
    [self.playerontainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(STATUSBARHEIGHT);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, self.videoHeight));
    }];
    
    [self.userView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(20);
        make.right.mas_equalTo(self.view).offset(-20);
        make.top.mas_equalTo(self.playerView.mas_bottom).offset(18);
        make.height.mas_equalTo(@40);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(20);
        make.right.mas_equalTo(self.view).offset(-20);
        make.top.mas_equalTo(self.userView.mas_bottom).offset(15);
    }];
    [self.commentTool mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.height.mas_equalTo(kTabBarHeight);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.titleLabel.mas_bottom);
        make.bottom.mas_equalTo(self.commentTool.mas_top);
    }];
    [self.shareView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.headerView);
        make.top.mas_equalTo(self.headerView).offset(20);
        make.height.mas_equalTo(@120);
    }];
    
    [self.headerLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.headerView);
        make.top.mas_equalTo(self.shareView.mas_bottom);
        make.height.mas_equalTo(@10);
    }];
    [self.allCommentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.headerView).offset(15);
        make.top.mas_equalTo(self.headerLine.mas_bottom);
        make.bottom.mas_equalTo(self.headerView);
    }];
    
    
    [self.view bringSubviewToFront:self.playerontainer];
    
    [self getAticleInfo];
    [self getAticleCommentInfo];

}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (!self.fullScreen) {
        [self.playerontainer mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.view);
            make.top.mas_equalTo(STATUSBARHEIGHT);
            make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, self.videoHeight));
        }];
    }
}

#pragma mark - CommentToolDelegate
-(void)commentToolSelectedIndex:(NSInteger)index{
    if (index == 0) {//评论
        
    }else if (index == 2) {//分享
        
    }
}
/// 评论文章
-(void)commentToolTextViewClick{
    self.commentSub = NO;
    [self.commentDict setObject:@(0) forKey:@"CommentID"];
    [self.inputToolbar.textInput becomeFirstResponder];
}
#pragma mark - ZInputToolbarDelegate
-(void)inputToolbar:(ZInputToolbar *)inputToolbar sendContent:(NSString *)sendContent {
    // 清空输入框文字
    if (self.commentSub) {
        [self.commentDict setObject:[NSString stringWithFormat:@"%@||%@",sendContent,self.commentModel.NikeName] forKey:@"Content"];
    }else{
        [self.commentDict setObject:sendContent forKey:@"Content"];
    }
    
    [FBNetworkTool get:@"articleapi/com.AddCommontInfo" parameters:self.commentDict showHUD:YES success:^(XMHttpResponseModel *responseModel) {
        if (responseModel.code == 200) {
            [inputToolbar sendSuccessEndEditing];
            
            ///请求成功重新请求评论列表
            [self getAticleCommentInfo];
        }
    } failure:^(NSError *error) {
        
    }];
}

///回复
-(void)replyWithModel:(AticleComment *)model{
    self.commentModel = model;
    self.commentSub = NO;
    [self.commentDict setObject:@(model.CommentID) forKey:@"CommentID"];
    [self.inputToolbar.textInput becomeFirstResponder];
}
///回复
-(void)replySubCommentWithModel:(AticleComment *)model{
    self.commentModel = model;
    self.commentSub = YES;
    [self.commentDict setObject:@(model.CommentID) forKey:@"CommentID"];
    [self.inputToolbar.textInput becomeFirstResponder];
}

- (void)playerKitContainer:(PlayerKitContainer *)playerContainer willAnimationWithType:(PlayerKitAnimationType)animationType {
    ///这个地方其实不准确，但目前可以作为判断全屏的依据
    if (animationType == PlayerKitAnimationTypeClockwise) {//全屏
        self.fullScreen = YES;
        // 禁用返回手势
        if ([self.rt_navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.rt_navigationController.interactivePopGestureRecognizer.enabled = NO;
        }
        self.navigationItem.leftBarButtonItem.customView.hidden = YES;
    }else if (animationType == PlayerKitAnimationTypeNone){//退出全屏
        self.fullScreen = NO;
        // 开启返回手势
  
        if ([self.rt_navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.rt_navigationController.interactivePopGestureRecognizer.enabled = YES;
        }
        self.navigationItem.leftBarButtonItem.customView.hidden = NO;

        [self viewDidLayoutSubviews];
    }
}

#pragma mark -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.commentArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 100;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString *viewIdentfier = @"commentHeaderView";
    CommentSectionView *sectionHeadView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:viewIdentfier];
    if(!sectionHeadView){
        sectionHeadView = [[CommentSectionView alloc] initWithReuseIdentifier:viewIdentfier];
    }
    WEAKSELF
    sectionHeadView.block = ^(AticleComment *model) {
        [weakSelf replyWithModel:model];
    };
    sectionHeadView.comment = self.commentArray[section];
    return sectionHeadView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    AticleComment * comment = self.commentArray[section];
    if (comment.CommentChildrens.count > 3) {
        return 4;
    }
    return comment.CommentChildrens.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentCell * cell = [CommentCell cellWithTableView:tableView];
    AticleComment * comment = self.commentArray[indexPath.section];
    cell.commentCount = comment.CommentChildrens.count;
    cell.nickName = comment.NikeName;
    
    AticleComment * subComment = comment.CommentChildrens[indexPath.row];
    subComment.isMore = indexPath.row == 3;
    cell.comment = subComment;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3) {
        MoreReplyView * moreView = [[MoreReplyView alloc] init];
        moreView.comment = self.commentArray[indexPath.section];
        [kAppWindow addSubview:moreView];
        [UIView animateWithDuration:0.24 animations:^{
            moreView.y = 0;
        }];
    }else{
        AticleComment * comment = self.commentArray[indexPath.section];
        [self replySubCommentWithModel:comment.CommentChildrens[indexPath.row]];
    }
}


#pragma mark -
- (void)getAticleInfo{
    NSDictionary * dict = @{@"MenuType":@(self.model.ID),
                            @"ID":@(self.model.ID)
                            };
    [FBNetworkTool get:@"articleapi/com.GetAticleInfo" parameters:dict showHUD:YES success:^(XMHttpResponseModel *responseModel) {
        if (responseModel.code == 200) {
            self.detailModel = [AticleDetailModel mj_objectWithKeyValues:responseModel.data];
            self.userView.detailModel = self.detailModel;
            self.titleLabel.text = self.detailModel.Title;
            self.commentTool.model = self.detailModel;
        }
    } failure:^(NSError *error) {
        
    }];
}
- (void)getAticleCommentInfo{
    NSDictionary * dict = @{@"CommentID":@"0",
                            @"ArticleID":@(self.model.ID),
                            @"PageInfo":@{@"CurrentPage":@(1),
                                          @"PageSize":@(10)
                                          },
                            };
    [FBNetworkTool get:@"articleapi/com.GetAticleCommentInfo" parameters:dict showHUD:YES success:^(XMHttpResponseModel *responseModel) {
        if (responseModel.code == 200) {
            self.commentArray = [AticleComment mj_objectArrayWithKeyValuesArray:responseModel.data];
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}



#pragma mark -

- (UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView new];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView = tableView;
    }
    return _tableView;
}
- (NewsCommentTool *)commentTool{
    if (!_commentTool) {
        _commentTool = [[NewsCommentTool alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49)];
        _commentTool.delegate = self;
    }
    return _commentTool;
}
- (ZInputToolbar *)inputToolbar{
    if (!_inputToolbar) {
        _inputToolbar = [[ZInputToolbar alloc] initWithFrame:CGRectMake(0,self.view.height, self.view.width, 49)];
        _inputToolbar.textViewMaxLine = 5;
        _inputToolbar.delegate = self;
        _inputToolbar.placeholderLabel.text = @"优质评论将会被优先展示";
        [self.view addSubview:_inputToolbar];
    }
    return _inputToolbar;
}
- (PlayerKitContainer *)playerontainer {
    if (!_playerontainer) {
        _playerontainer = [[PlayerKitContainer alloc] init];
        _playerontainer.delegate = self;
        _playerontainer.playbackLoops = YES;
        _playerontainer.mediaPath = VideoDataSourceURLPath;
        [_playerontainer buildInterface];
    }
    return _playerontainer;
}
-(NSMutableDictionary *)commentDict{
    if (!_commentDict) {
        _commentDict = [NSMutableDictionary dictionary];
        [_commentDict setObject:@(self.detailModel.ID) forKey:@"ArticleID"];
        [_commentDict setObject:@([UserAccountTool account].UserId) forKey:@"UserID"];
    }
    return _commentDict;
}




-(void)dealloc{
    [self.playerontainer.playerView.player pause];
    [self.playerontainer.playerView.player replaceCurrentItemWithPlayerItem:nil];
    self.playerontainer = nil;
}

@end








